

let EventEmitter = require('eventemitter3');
let mixins = require('../utils/mixins');

const templateDiv = `
    <span id="name"></span>
    min:<input type="number" class="range_1" id="min">
    max:<input type="number" class="range_1" id="max">
    cur:<input type="number" class="range_1" id="cur">
`;

const EventName = {
    Cur:'cur',
    Min:'min',
    Max:'max',
};

const DefaultOption = {
    cur : 0.5,
    min : 0,
    max : 2,
    step : 0.1,
    name:''
};


// TODO:
// min max cur 范围判断
class Range {
    constructor(options = {}){

        mixins(options,DefaultOption);
        let cur = options.cur;
        let min = options.min;
        let max = options.max;
        let step = options.step;
        let name = options.name;

        // data
        this._min = this._max = this._cur = -1;

        this.element = globalThis.document.createElement('div');
        this.element.innerHTML = templateDiv;

        this.nameEl= this.element.querySelector('#name');
        this.nameEl.innerText = name;

        this.minEl = this.element.querySelector('#min');
        this.maxEl = this.element.querySelector('#max');
        this.curEl = this.element.querySelector('#cur');

        // 添加step
        this.minEl.setAttribute('step',step+'');
        this.maxEl.setAttribute('step',step+'');
        this.curEl.setAttribute('step',step+'');

        // 绑定
        this.curEl.addEventListener('change',this.onCurUIChange.bind(this),false);
        this.minEl.addEventListener('change',this.onMinUIChange.bind(this),false);
        this.maxEl.addEventListener('change',this.onMaxUIChange.bind(this),false);

        this.ee = new EventEmitter();
        this.ee.on(EventName.Cur,this.onCurDataChange,this);
        this.ee.on(EventName.Min,this.onMinDataChange,this);
        this.ee.on(EventName.Max,this.onMaxDataChange,this);

        this.setCur(cur);
        this.setMin(min);
        this.setMax(max);
    }

    // data->ui
    onCurDataChange(newValue){
        this.curEl.value = newValue;
    }
    onMinDataChange(newValue){
        this.minEl.value = newValue;
    }
    onMaxDataChange(newValue){
        this.maxEl.value = newValue;
    }

    // set
    setCur(newValue){
        this._cur = newValue;
        this.ee.emit(EventName.Cur,this._cur);
    }

    setMin(newValue){
        this._min = newValue;
        this.ee.emit(EventName.Min,this._min);
    }

    setMax(newValue){
        this._max = newValue;
        this.ee.emit(EventName.Max,this._max);
    }

    // ui->data
    onCurUIChange(){
        this.setCur(parseFloat(this.curEl.value));
        console.log('cur:',this._cur);
    }

    onMinUIChange(){
        this.setMin(parseFloat(this.minEl.value));
        console.log('min:',this._min);
    }
    onMaxUIChange(){
        this.setMax(parseFloat(this.maxEl.value));
        console.log('max:',this._max);
    }

    getCur(){return this._cur;}
    getMin(){return this._min;}
    getMax(){return this._max;}
}

module.exports = Range;
